package com.neusoft.mid.msf.common.context;

import com.neusoft.mid.msf.common.constant.CommonContants;
import com.neusoft.mid.msf.common.util.StringHelper;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: pangu
 * @description: 系统上下文对象, 实现ThreadLocal
 * @author: fengjd
 * @create: 2022-07-26 11:25
 **/
public class BaseContextHander {
    public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

    /**
     * 上下文中,设置key/value 键值对
     * @param key
     * @param value
     */
    public  static void  set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map==null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        map.put(key,value);

    }

    /**
     * 从上下文中,获取key对应的value值
     * @param key
     * @return
     */
    public static Object get(String key){
        Map<String, Object> map = threadLocal.get();
        if (map==null) {
            map = new HashMap<>();
            threadLocal.set(map);
        }
        return map.get(key);

    }

    public static  String getUserID(){
        Object value = get(CommonContants.CONTEXT_KEY_USER_ID);
        return  returnObjectValue(value);

    }

    public static String getUserName(){
        Object value = get(CommonContants.CONTEXT_KEY_USER_NAME);
        return  returnObjectValue(value);
    }

    /**
     * 从上下文中, 当前的鞥路系统的用户姓名
     * @return
     */
    public static String getName(){
        Object value = get(CommonContants.CONTEXT_KEY_USER_NAME);
        return StringHelper.getObjectValue(value);

    }

    /**
     * 从上下文文中,当前登录系统的用户的token信息
     * @return
     */
    public static  String getToken(){
        Object value = get(CommonContants.CONTEXT_KEY_USER_TOKEN);
        return StringHelper.getObjectValue(value);

    }

    public static  void  setToken(String token){
        set(CommonContants.CONTEXT_KEY_USER_TOKEN, token);
    }

    public static void setName(String name) {
        set(CommonContants.CONTEXT_KEY_USER_NAME, name);
    }

    public static  void setUserID(String userID){
        set(CommonContants.CONTEXT_KEY_USER_ID, userID);
    }

    public static  void setUsername(String username){
        set(CommonContants.CONTEXT_KEY_USER_NAME, username);
    }

    /**
     * 清空threadLocal
     */
    public static void  remove(){
        threadLocal.remove();
    }

    private static  String returnObjectValue(Object value) {
        return value == null ? null : value.toString();
    }
}
